<template>
  <div style="margin-right: 10px">
    <el-card style="margin-bottom: 16px">
      <div slot="header" style="display: flex; justify-content: space-between">
        <span><i class="el-icon-collection"></i>{{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }} Top{{
          topNumber
        }}销售报表分析-本年{{ dataYear.dataYear }}</span>
        <span>
          产品组合：
          <el-select v-model="topNumber" placeholder="top款" style="width: 100px; height: 30px; margin-left: 5px"
            @change="changeView">
            <el-option v-for="dict in topNumberList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportI">导出</el-button>
        </span>
        <!-- <span
                      ><i class="el-icon-collection"></i>
                      {{ query.salesGrade? query.salesGrade: query.proBrandList + " " }}年度完成率</span
                    > -->
      </div>
      <tableDataI :tableDataList="tableDataI" :topNumber="topNumber" @handleSortChangeI="handleSortChangeI" />
      <pagination v-show="totalI > 0" :limit.sync="pageReqI.thisPageSize" :page.sync="pageReqI.pageNum" :total="totalI"
        @pagination="getselectProductLevelAnalysis"></pagination>
    </el-card>

    <el-card style="margin-bottom: 16px">
      <div slot="header" style="display: flex; justify-content: space-between">
        <span><i class="el-icon-collection"></i>{{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }} Top{{
          topNumber
        }}销售报表分析-上一年{{ dataYear.lastdataYear }}</span>
        <span>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExportII">导出</el-button>
        </span>
      </div>
      <tableDataII :tableDataList="tableDataII" :topNumber="topNumber" @handleSortChangeII="handleSortChangeII" />
      <pagination v-show="totalII > 0" :limit.sync="pageReqII.thisPageSize" :page.sync="pageReqII.pageNum"
        :total="totalII" @pagination="getselectProductLevelAnalysisLastYear"></pagination>
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        {{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}品类销售分析(单位：万)
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24">
          <!-- <barLineIII :echartDataSku="barLineChart" /> -->
          <ve-histogram :data="barLineChart" :y-axis="yAxis" :extend="chartExtend" :settings="chartSettingscompleteRate"
            style="width: 100%; height: 100%"></ve-histogram>
        </el-col>
        <el-col :span="8" :xs="24">
          <!-- <tableList :tableDataList="categoryNewCountYoyList"
        /> -->
          <el-table :data="barLineData" style="width: 100%" border :height="350">
            <el-table-column prop="year" label="年份" width="125">
              <template slot-scope="scope">
                <span style="white-space: normal;">
                  {{ scope.row.year }}<br />{{ scope.row.dateRange }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :formatter="stateFormat" prop="salesAmount" label="全品类销售额" width="150">
              <template slot-scope="scope">
                <span v-if="scope.row.year == '同期比'">
                  {{ scope.row.salesAmount }}%
                </span>

                <span v-else>
                  {{ scope.row.salesAmount.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  }) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :formatter="stateFormat" prop="salesAmountTop" label="top10销售额" width="150">
              <template slot-scope="scope">
                <span v-if="scope.row.year == '同期比'">
                  {{ scope.row.salesAmountTop }}%
                </span>

                <span v-else>
                  {{ scope.row.salesAmountTop.toLocaleString('en-US', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                  }) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :formatter="PerseFormat" prop="salesAmountTopRatio" label="top10销售占比" width="100">
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- <el-card style="margin-bottom: 16px">
      <div slot="header">
        产品上新分析
       
      </div>
      <barLine :echartDataSku="barLineChart" />
      <tableList :tableDataList="barLineData" />
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        产品品类上新分析
        
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24"
          ><barLine :echartDataSku="categoryNewCountYoyChart" />
        </el-col>
        <el-col :span="8" :xs="24">
          <tableList :tableDataList="categoryNewCountYoyList"
        /></el-col>
      </el-row>
    </el-card>
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        新品层级分布
        
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24"
          ><barLine :echartDataSku="operationLevelNewCountYoyChart" />
        </el-col>
        <el-col :span="8" :xs="24">
          
          <el-table
            :data="operationLevelNewCountYoyList"
            style="width: 100%"
            border
            :height="350"
          >
            <el-table-column
              prop="operationLevel"
              label="层级"
              width="125"
            ></el-table-column>
            <el-table-column prop="newQuantity" label="2023年" width="150">
            </el-table-column>
            <el-table-column
              prop="yoyNewQuantity"
              label="2024年"
              width="150"
            ></el-table-column>
            <el-table-column
              prop="newQuantityYoy"
              label="同期比"
              width="100"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="10">
      <el-col :span="12" :xs="24" v-for="(item, i) in xqpjTableData" :key="i">
        <el-card style="margin-bottom: 16px">
          <div slot="header">
            <span
              ><i class="el-icon-collection"></i>
              {{ item.cpbm }}上新品类层级分布</span
            >
          </div>
          <barLine :echartDataSku="item.name" />
        </el-card>
      </el-col>
    </el-row> -->
  </div>
</template>
<script>
import * as echarts from "echarts/lib/echarts.js";
import {
  selectProductLevelAnalysis,
  selectProductLevelAnalysisLastYear,
  selectProductSaleRatioTop,
  productSaleRatioTopComparison,
} from "@/api/productStructure/BiCategoryBasicsDwd";
import LineChart from "./components/LineChart";
import barLineIII from "./components/barLineIII";
import tableList from "./components/table";
import tableDataI from "./components/tableDataI";
import tableDataII from "./components/tableDataII";

export default {
  props: {
    query: {
      type: Object,
      default: () => { },
    },
    dataYear: {
      type: Object,
      default: () => { },
    },
  },
  components: {
    barLineIII,
    LineChart,
    tableList,
    tableDataI,
    tableDataII,
  },

  data() {

    this.chartSettingscompleteRate = {
      // "0.[00]a",
      yAxisType: ["0.[00]", "0.[00]%"],
      showLine: ["top10销售占比"],
      yAxisName: ["数值轴", "比率轴"],
      axisSite: {
        right: ["top10销售占比"],
      },
    };
    this.chartExtend = {
      series(v) {
        v.forEach((i, index) => {
          i.barWidth = 15;
          i.barGap = 0;
          if (i.type !== "line") {
            i.label = {
              show: true,
              position: index === 0 ? 'left' : 'right',
              color: "#333",
              fontSize: 12,
              // formatter: ({ value }) => value.toFixed(2),
              formatter: ({ value }) =>
                value.toLocaleString('en-US', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
            };
          }
        });
        return v;
      },
      xAxis(v) {
        v.forEach((i) => {
          i.show = true;
          i.splitLine = { show: false };
          i.axisTick = { show: true };
          i.axisLine = { show: true };
        });
        return v;
      },
    };
    this.yAxis = [
      {
        name: "数值轴",
        show: true,
        splitLine: { show: false }, //去除网格线
        //设置轴线的属性
        axisLabel: {
          color: "#ccc", // 字体
        },
        axisTick: {
          //y轴刻度线
          show: true,
        },
        axisLine: {
          //y轴
          show: true,
        },
      },
      {
        name: "比率轴",
        show: true,
        splitLine: { show: false }, //去除网格线
        //设置轴线的属性
        axisLabel: {
          color: "red",
          formatter: (value) => `${(value * 100).toFixed(0)}%`, // 强制显示百分比
        },
        axisTick: {
          //y轴刻度线
          show: true,
        },
        axisLine: {
          //y轴
          show: true,
        },
      },
    ];
    return {
      ParamsII: { isAsc: true, property: "salesAmount" },
      ParamsI: { isAsc: true, property: "salesAmount" },
      queryParamsI: {},
      //本年
      totalI: 0,
      pageReqI: {
        pageNum: 1,
        thisPageSize: 10,
      },
      //上一年
      queryParamsII: {},
      totalII: 0,
      pageReqII: {
        pageNum: 1,
        thisPageSize: 10,
      },
      // TOP5TOP5TOP10TOP30TOP50TOP100TOP200TOP300
      topNumber: 10,
      topNumberList: [
        {
          value: 5,
          label: "TOP5",
        },
        {
          value: 10,
          label: "TOP10",
        },
        {
          value: 30,
          label: "TOP30",
        },
        {
          value: 50,
          label: "TOP50",
        },
        {
          value: 100,
          label: "TOP100",
        },
        {
          value: 200,
          label: "TOP200",
        },
        {
          value: 300,
          label: "TOP300",
        },
      ],
      tableDataI: [], // 用于存储转换后的数据
      tableDataII: [], // 用于存储转换后的数据
      months: [], // 用于存储所有月份

      operationLevelNewCountYoyChart: {},
      operationLevelNewCountYoyList: [],

      categoryNewCountYoyChart: {},
      categoryNewCountYoyList: [],
      //对比
      barLineChart: {},
      barLineData: [],

      xqpjTableData: [],
    };
  },
  watch: {
    query: {
      handler: function (newnew, oldold) {
        this.getselectProductLevelAnalysis();
        this.getselectProductLevelAnalysisLastYear();
        this.getselectProductSaleRatioTop();
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    // this.getList();
  },
  methods: {
    getselectProductSaleRatioTop() {
      selectProductSaleRatioTop(this.query).then((response) => {
        this.barLineData = response;
        // this.barLineChart = {
        //   columns: ["品类", "全品类销售额", "top10销售额"],
        //   rows: [],
        // };

        // response.forEach((item) => {
        //   if (item.year != '同期比') {
        //     this.barLineChart.rows.push({

        //       品类: item.year,
        //       全品类销售额: item.salesAmount,
        //       top10销售额: item.salesAmountTop,
        //       同比: item.salesAmountTopRatio ? item.salesAmountTopRatio : 0,
        //     });
        //   }

        // });
      });
      productSaleRatioTopComparison(this.query).then((response) => {
        // this.barLineData = response;
        this.barLineChart = {
          columns: ["品类", "全品类销售额", "top10销售额", 'top10销售占比'],
          rows: [],
        };

        response.forEach((item) => {
          if (item.year != '同期比') {
            this.barLineChart.rows.push({

              品类: item.year,
              全品类销售额: item.salesAmount,
              top10销售额: item.salesAmountTop,
              top10销售占比: item.salesAmountTopRatio ? item.salesAmountTopRatio / 100 : 0,
            });
          }
        });
        console.log(JSON.stringify(this.barLineChart.rows));
      });
    },
    changeView() {
      this.pageReqI.pageNum = 1;
      this.pageReqII.pageNum = 1;
      this.getselectProductLevelAnalysis();
      this.getselectProductLevelAnalysisLastYear();
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在加载，请稍候！");
    },
    handleSortChangeI(queryParams) {
      // console.log(JSON.stringify(queryParams));
      this.ParamsI = queryParams
      this.getselectProductLevelAnalysis()
    },
    getselectProductLevelAnalysis() {
      this.queryParamsI = {
        topNumber: this.topNumber,
        ...this.query,
        ...this.pageReqI,
        ...this.ParamsI
      };
      this.openLoading();
      selectProductLevelAnalysis(this.queryParamsI).then((response) => {
        this.$modal.closeLoading();
        this.tableDataI = response.data;
        this.totalI = response.totalCount;
      });
    },
    handleSortChangeII(queryParams) {
      // console.log(JSON.stringify(queryParams));
      this.ParamsII = queryParams
      this.getselectProductLevelAnalysisLastYear()
    },
    getselectProductLevelAnalysisLastYear() {
      this.queryParamsII = {
        topNumber: this.topNumber,
        ...this.query,
        ...this.pageReqII,
        ...this.ParamsII
      };
      selectProductLevelAnalysisLastYear(this.queryParamsII).then(
        (response) => {
          this.tableDataII = response.data;
          this.totalII = response.totalCount;
        }
      );
    },
    handleExportI() {
      this.download(
        "productStructure/BiCategoryBasicsDwd/selectProductLevelAnalysisExport",
        {
          ...this.queryParamsI,
        },
        `selectProductLevelAnalysisExport_${new Date().getTime()}.xlsx`
      );
    },
    handleExportII() {
      this.download(
        "productStructure/BiCategoryBasicsDwd/selectProductLevelAnalysisLastYearExport",
        {
          ...this.queryParamsII,
        },
        `selectProductLevelAnalysisLastYearExport_${new Date().getTime()}.xlsx`
      );
    },

    getcategoryNewCountYoy() {
      categoryNewCountYoy(this.query).then((response) => {
        this.categoryNewCountYoyList = response.categorySaleTendData;
        this.categoryNewCountYoyChart = {
          columns: ["品类", "上新数量", "上一年上新数量", "同比"],
          rows: [],
        };

        response.itemNewTimeYoyList.forEach((item) => {
          this.categoryNewCountYoyChart.rows.push({
            品类: item.category,
            上新数量: item.newQuantity,
            上一年上新数量: item.yoyNewQuantity,
            同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
          });
        });
      });
    },
    getoperationLevelNewCountYoy() {
      operationLevelNewCountYoy(this.query).then((response) => {
        this.operationLevelNewCountYoyList = response;
        this.operationLevelNewCountYoyChart = {
          columns: ["品类", "上新数量", "上一年上新数量", "同比"],
          rows: [],
        };

        response.forEach((item) => {
          this.operationLevelNewCountYoyChart.rows.push({
            品类: item.operationLevel,
            上新数量: item.newQuantity,
            上一年上新数量: item.yoyNewQuantity,
            同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
          });
        });
      });
    },
    getselectProTypeList(category) {
      operationLevelNewCountYoy({ category: category, ...this.query }).then(
        (response) => {
          let obj = {
            columns: ["品类", "上新数量", "上一年上新数量", "同比"],
            rows: [],
          };
          response.forEach((item) => {
            obj.rows.push({
              品类: item.operationLevel,
              上新数量: item.newQuantity,
              上一年上新数量: item.yoyNewQuantity,
              同比: item.newQuantityYoy ? item.newQuantityYoy : 0,
            });
          });
          this.xqpjTableData.forEach((item) => {
            if (item.cpbm == category) {
              item.name = obj;
            }
          });
        }
      );
    },
    getselectCategorySaleTend(property) {
      selectCategorySaleTend(this.query).then((response) => {
        this.tableData = []; // 用于存储转换后的数据
        this.months = []; // 用于存储所有月份
        // 提取所有月份
        response.categorySaleTendData.forEach((item) => {
          for (const month in item.keywordProperty) {
            // const element = array[index];
            if (!this.months.includes(month)) {
              this.months.push(month);
            }
          }
        });
        console.log(JSON.stringify(this.months));

        response.categorySaleTendData.forEach((item) => {
          const row = {
            dataDateUnit: item.dataDateUnit,
            salesData: [],
          };
          this.months.forEach((month) => {
            row.salesData.push(item.keywordProperty[month] || 0);
          });
          this.tableData.push(row);
        });

        // return;

        let order = { date: [], data: [] };
        order.date = response.categorySaleStatisticsTend.map(
          (item) => item.dataDateUnit
        );
        response.categorySaleStatisticsTend.forEach((item) => {
          order.data.push(item.keywordProperty);
        });
        const xData = order.date;

        console.log(JSON.stringify(order.data));
        const keyArray = Object.keys(order.data[1]);
        const series = [];
        keyArray.forEach((key) => {
          series.push({
            name: key,
            data: order.data.map((item) => item[key]),
            type: "line",
          });
        });

        const option = {
          grid: {
            left: "5%",
            top: "10%",
            right: "2%",
            bottom: "10%",
          },
          // 提示框
          tooltip: { trigger: "axis" },
          xAxis: {
            data: xData,
          },
          yAxis: {},
          legend: {
            data: keyArray,
          },
          series,
        };

        const E = echarts.init(this.$refs[property]);

        E.setOption(option);
      });
    },
  },
};
</script>
